package cn.yiya.shiji.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.ChooseGoodsActivity;
import cn.yiya.shiji.activity.OrderDetailActivity;
import cn.yiya.shiji.adapter.OrderListAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MapRequest;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.OrderListObject;

/**
 * Created by jerry on 2016/2/23.
 */
public class AllOrderFragment extends BaseFragment {
    private RecyclerView recyclerView;
    private OrderListAdapter orderListAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayoutManager linearLayoutManager;
    private int lastVisiableItem;
    private int refreshtime = 0;
    boolean loadMore = true;
    private Handler handler;
    private LinearLayout llNothing;
    public static boolean isFresh = true;
    boolean isVisiable = false;
    boolean isInitView = false;
    private int ALL_ORDER = 0;
    private final int OFFSET_TIMES = 10;
    private int limit = 10;
    private int offset = 0;
    private static final String ALLSTATUS = "0";

    private int arraylistSize;     // 用于判断是否上拉加载
    private View mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(Looper.getMainLooper());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.order_layout, container, false);
        initViews();
        initEvents();
        isInitView = true;
        init();
        return mView;
    }

    @Override
    protected void initViews() {
        recyclerView = (RecyclerView)mView.findViewById(R.id.recyclerview);
        swipeRefreshLayout = (SwipeRefreshLayout)mView.findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        orderListAdapter = new OrderListAdapter(getActivity(), handler, 2);
        recyclerView.setAdapter(orderListAdapter);
        llNothing = (LinearLayout)mView.findViewById(R.id.ll_nothing);
    }

    @Override
    protected void initEvents() {
        if (isVisiable) {
            getAllOrderList(offset, limit);
            initEvent();
        }
    }

    @Override
    protected void init() {

    }

    private void initEvent() {

        orderListAdapter.setOnItemClickListener(new OrderListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String orderno, String suborderno, int type) {
                if (type == orderListAdapter.OTHER) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), OrderDetailActivity.class);
                    intent.putExtra("orderno", orderno);
                    intent.putExtra("orderId", suborderno);
                    startActivityForResult(intent, ALL_ORDER);
                } else if (type == orderListAdapter.SHAREORDER) {
                    Intent intent = new Intent(getActivity(), ChooseGoodsActivity.class);
                    intent.putExtra("orderno", orderno);
                    intent.putExtra("orderId", suborderno);
                    startActivity(intent);
                }
            }

        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshtime = 0;
                getAllOrderList(refreshtime, limit);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && orderListAdapter.getItemCount() == lastVisiableItem + 1) {
                    if (arraylistSize == 10) {
                        ++refreshtime;
                        getAllOrderList(refreshtime * OFFSET_TIMES, limit);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                isFresh = false;
                lastVisiableItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void getAllOrderList(final int offset, int limit) {
        if (!swipeRefreshLayout.isRefreshing()) {
            showPreDialog("正在加载");
        }
        new RetrofitRequest<OrderListObject>(ApiRequest.getApiShiji().getAllOrderList(
                MapRequest.setAllOrderList(ALLSTATUS,offset))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    OrderListObject obj = (OrderListObject) msg.obj;
                    if (obj.list != null && obj.list.size() > 0) {
                        arraylistSize = obj.list.size();
                        llNothing.setVisibility(View.GONE);
                        swipeRefreshLayout.setVisibility(View.VISIBLE);
                        if (offset > 0) {                                               // 加载更多
                            orderListAdapter.getArrayList().addAll(obj.list);
                        } else {
                            orderListAdapter.setArrayList(obj.list);
                        }
                        orderListAdapter.notifyDataSetChanged();
                    } else if (offset == 0) {                                           // 第一次加载
                        llNothing.setVisibility(View.VISIBLE);
                        swipeRefreshLayout.setVisibility(View.GONE);
                    } else {
                        llNothing.setVisibility(View.GONE);
                        swipeRefreshLayout.setVisibility(View.VISIBLE);
                    }
                }
                hidePreDialog();
                if (swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisiable = true;
            if (isInitView && isVisiable) {
                getAllOrderList(offset, limit);
                initEvent();
            }
        } else {
            isVisiable = false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ALL_ORDER) {
            if (resultCode == getActivity().RESULT_OK) {
                getAllOrderList(offset, limit);
            }
        }
    }
}
